package com.sky.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;

    /**
     * 清理超时未支付订单
     */
    //@Scheduled(cron = "0 * * * * ?")
    //@Scheduled(cron = "1/5 * * * * ?")
    public void processTimeOutOrder(){
        log.info("定时清理超时订单，当前时间：{}", LocalDateTime.now());

        //当前时间减去十五分钟和订单时间对比，如果大于，修改状态
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);

        List<Orders> orders = orderMapper.selectList(Wrappers.<Orders>lambdaQuery().
                eq(Orders::getStatus, Orders.PENDING_PAYMENT)
                .le(Orders::getOrderTime, time));
        //判断是否有值,有值，修改
        if (CollectionUtils.isNotEmpty(orders)){
            //用集合装，然后批量修改，优化性能
            List<Orders> list = new ArrayList<>();
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付,订单取消");
                order.setCancelTime(LocalDateTime.now());
                list.add(order);
            }
            orderService.updateBatchById(list);
            log.info("定时清理超时未支付订单完成");
        }
    }

    /**
     * 每天凌晨一点（打烊一小时后清理未送达订单）
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processDeliverOrder(){
        log.info("定时处理派送中的订单，当前时间：{}",LocalDateTime.now());
        //当前时间减去60分钟和订单时间对比，如果大于，修改状态
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);

        List<Orders> orders = orderMapper.selectList(Wrappers.<Orders>lambdaQuery().
                eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)
                .le(Orders::getOrderTime, time));
        //判断是否有值,有值，修改
        if (CollectionUtils.isNotEmpty(orders)){
            //用集合装，然后批量修改，优化性能
            List<Orders> list = new ArrayList<>();
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                list.add(order);
            }
            orderService.updateBatchById(list);
            log.info("定时清理未送达订单完成");
        }
    }
}
